// RGB LED - Automatic or Manual Color Cycling

/*  Common anode connected w/ common lead connected to 
the positive 5v terminal.  Each individual negative lead is
connected to a 220 Ohm resistor and then connected to one
of the PWM termminals.  The potentiometer is connected to
ground, A0, and 5v.  */


// Comment this line out if you are using a common-cathode LED
#define COMMON_ANODE_LED

#define RED_PIN   11
#define GREEN_PIN 3
#define BLUE_PIN  9
#define POT_PIN   A0


void SetLEDColor(int red, int green, int blue);
void ColorMap1(int color);


void setup()
{
//  Serial.begin(9600);  // Start Serial
}

void loop()
{
  // You can use either of the methods here by commenting out (or deleting) the 
  // one you don't want.

  // Automacially iterate through the colors
  for (int i=0; i<2040; i++) {
    ColorMap1(i);
    delay(10);
  }

//  // Use the potentiometer to set the color
//  int pot;
//  pot = analogRead(POT_PIN);
//  ColorMap1(map(pot, 0, 1023, 0, 2039));
}

// This function takes conventional RGB values and sets the LED color 
// accordingly, inverting the values if necessary for a common-anode RGB LED.
void SetLEDColor(int red, int green, int blue)
{
  constrain(red,   0, 255);
  constrain(green, 0, 255);
  constrain(blue,  0, 255);

#ifdef COMMON_ANODE_LED
    red   = 255 - red;
    green = 255 - green;
    blue  = 255 - blue;
#endif

  analogWrite(RED_PIN,   red);
  analogWrite(GREEN_PIN, green);
  analogWrite(BLUE_PIN,  blue);

//  Serial.print(red);
//  Serial.print("\t");
//  Serial.print(green);
//  Serial.print("\t");
//  Serial.println(blue);
}

// This function take a single number (0-2039) and maps it to RGB color values.
void ColorMap1(int color)
{
  int red, green, blue;

  color %= 2040;

  if (color < 256) {
    // transition to red
    red   = color;
    green = 0;
    blue  = 0;
  } else if (color < 511) {
    // transition to yellow
    red   = 255;
    green = map(color, 256, 510, 1, 255);
    blue  = 0;
  } else if (color < 766) {
    // transition to green
    red   = map(color, 511, 765, 254, 0);
    green = 255;
    blue  = 0;
  } else if (color < 1021) {
    // transition to aqua
    red   = 0;
    green = 255;
    blue  = map(color, 766, 1020, 1, 255);
  } else if (color < 1276) {
    // transition to white
    red   = map(color, 1021, 1275, 1, 255);
    green = 255;
    blue  = 255;
  } else if (color < 1531) {
    // transition to violet
    red   = 255;
    green = map(color, 1276, 1530, 254, 0);
    blue  = 255;
  } else if (color < 1786) {
    // transition to blue
    red   = map(color, 1531, 1785, 254, 0);
    green = 0;
    blue  = 255;
  } else { //color < 2040
    // transition to black (all off)
    red   = 0;
    green = 0;
    blue  = map(color, 1786, 2039, 254, 1);
  }

  SetLEDColor(red, green, blue);
}

